package com.example.demo.leetcode.top100;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname _51岛屿数量
 * @description
 * @date 2023/06/18 10:34
 * <p>
 * ******************************************************
 */
public class _51岛屿数量 {

    public int numIslands(char[][] grid) {
        int res = 0;
        int m = grid.length, n = grid[0].length;
        // 遍历 grid
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == '1') {
                    res++;
                    land(grid, i, j);
                }
            }
        }
        return res;
    }

    private void land(char[][] grid, int i, int j) {
        // 超界判断
        int m = grid.length, n = grid[0].length;
        if (i < 0 || i >= m || j < 0 || j >= n) {
            return;
        }

        if (grid[i][j] == '0') {
            return;
        }

        // 岛屿变水
        grid[i][j] = '0';

        land(grid, i + 1, j);
        land(grid, i - 1, j);
        land(grid, i, j + 1);
        land(grid, i, j - 1);
    }
}
